<template>
  <!--部门管理-->
  <div class="app-container">
    <el-form class="jc_search_wrap" v-model="searchList">
      <label>名称</label><el-input v-model="searchList.deptName"></el-input>
      <el-button @click="searchRows"><i class="el-icon-search"></i>查询</el-button>
    </el-form>
    <el-button-group class="jc_btn_wrap jc_btn_left">
      <el-button @click="createRow"><i class="jc_icon el-icon-plus"></i>新增部门</el-button>
      <el-button @click="editRow"><i class=""></i>编辑</el-button>
      <el-button @click="deleteRow"><i class=""></i>删除</el-button>
    </el-button-group>
    <el-table :height="tableHeight" @cell-click="rowsClick" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row class="jc_table_wrap"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="80px">
      </el-table-column>
      <el-table-column label='名称'>
        <template scope="scope">
          <!--<img src="../../assets/dw_icon/arrow_right.png" v-if="scope.row.status===true" class="jc_arrow">
          <img src="../../assets/dw_icon/arrow_down.png" v-else-if="scope.row.status===false" class="jc_arrow">
          <span v-else="scope.row.status==='noshow'"></span>-->
          <span v-if="scope.row.hasSpace===true" style="color:transparent;">1111</span>
          <img src="../../assets/dw_icon/arrow_right.png" v-if="scope.row.status===true" class="jc_arrow">
          <img src="../../assets/dw_icon/arrow_down.png" v-else-if="scope.row.status === false" class="jc_arrow">
          <!--<img src="../../assets/icon/icon_cancel.png" v-else ="scope.row.status === 'noChildren'" class="jc_arrow">-->
          <span v-else ="scope.row.status === 'noChildren'" style="color:transparent;">1></span>
          {{scope.row.deptName}}
        </template>
      </el-table-column>
      <el-table-column label='创建时间'>
        <template scope="scope">
          {{scope.row.createTime}}
        </template>
      </el-table-column>
      <el-table-column label='自己加的状态码'>
        <template scope="scope">
          {{scope.row.status}}
        </template>
      </el-table-column>
      <el-table-column label='parentId'>
        <template scope="scope">
          {{scope.row.parentId}}
        </template>
      </el-table-column>
      <el-table-column label='编号'>
        <template scope="scope">
          {{scope.row.deptId}}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination layout="prev, pager, next" :total="total" @current-change="changePage" :page-size="15"/>
    <!--新建-->
    <el-dialog title="新建部门" :visible.sync="create_visible" class="jc_dialog_wrap">
      <el-form :model="form_create" label-width="120px">
        <el-form-item label="部门名称">
          <el-input v-model="form_create.deptName"></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-tree style="width: 300px;":data="treeDeptData" leafOnly show-checkbox node-key="deptId" :props="defaultProps" ref="tree" :check-strictly="true" @check-change="handleClick"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCreateForm">确定</el-button>
        <el-button @click="create_visible=false">取消</el-button>
      </div>
    </el-dialog>
    <!--编辑-->
    <el-dialog title="编辑部门" :visible.sync="edit_visible" class="jc_dialog_wrap">
      <el-form :model="form_edit" label-width="120px">
        <el-form-item label="部门名称">
          <el-input v-model="form_edit.deptName"></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-tree style="width: 300px;":data="treeDeptData" leafOnly show-checkbox node-key="deptId" :accordion="true" :props="defaultProps" ref="tree" :check-strictly="true" :default-checked-keys="editDept" :default-expanded-keys="editDept" @check-change="handleClick"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确定</el-button>
        <el-button @click="edit_visible=false">取消</el-button>
      </div>
    </el-dialog>
    <!--详情-->
    <el-dialog title="角色详情" :visible.sync="detail_visible" class="jc_dialog_wrap">
      <el-form :model="form_detail" label-width="120px">
        <el-form-item label="角色名">
          <el-input v-model="form_detail.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form_detail.createTime" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detail_visible=false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import * as Dept from "../../api/systemApi/department";

  export default {
    components: {

    },
    data() {
      return {
        searchList: {},
        list: [],
        listAll : [{status: ''}],
        total: 0,
        create_visible: false,
        detail_visible: false,
        edit_visible: false,
        form_create: {},
        form_detail: {},
        form_edit: {},
        multipleSelection: [],
        tableClose: true,
        treeDeptData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        editDept: [],
        i_tree:0, //单选时用
      }

    },
    created() {
      this.fetchData();
      this.getDeptList();

    },
    methods: {
      fetchData(p=1) {
        this.list = []; //先清空数据
        this.listLoading = true;
        var params = this.searchList;
        Dept.getDepartmentList(params).then(data => {
          this.listLoading = false;
          this.listAll = data;
          for(var j= 0;j<this.listAll.length;j++) { //总的数据listAll的状态status都为noshow
              this.listAll[j].status = 'noChildren';
          }
          for(var i = 0;i<this.listAll.length;i++){
              if(this.listAll[i].parentId === 0) {
                this.list.push(this.listAll[i]);//list 打开页面的数据
              }
          }
          for(var i in this.listAll) {//判断list中的行是否有子集 有子集 status为true 显示向右箭头
              for(var j in this.list) {
                  if(this.listAll[i].parentId === this.list[j].deptId) {
                    this.list[j].status = true;
                  }
              }
          }
          for(var i in this.list){//没有子集的行 没有icon  (但为了对其 给一个白的icon 对齐用)
              if(this.list[i].status !== true) {
                this.list[i].status = 'noChildren';
              }
          }
        })
      },
      rowsClick(row) {
        if(row.status) { //当状态为true时  向里面加数据
          var addArr = []; //获得点击行的子集
          for(var i in this.listAll) {
            if(this.listAll[i].parentId === row.deptId) {
              addArr.push(this.listAll[i]); //子集存在addArr中
            }
            //判断addArr中 是否还有子集
            for (var j in addArr) {
              if (this.listAll[i].parentId === addArr[j].deptId) {
                addArr[j].status = true;
                addArr[j].hasSpace = true;
              }else {
                addArr[j].hasSpace = true;
              }
            }
          }
          //console.log('addArr',addArr);
          var add; //子集应该追加在list中的位置
          for(var j in this.list) {
            if(this.list[j].deptId ===row.deptId) {
              add = Number(j) + 1;
            }
          }
          //console.log('add',add);
          //正式追加
          for(var k in addArr) {
            this.list.splice(Number(k)+Number(add),0,addArr[k]);
            //把状态改成false
            for(var i in this.list) {
              if(this.list[i].deptId === row.deptId) {
                this.list[i].status = false;
              }
            }
          }
        }else {//当状态为true时  从里面取出去
          console.log('row',row);

          var addArr = []; //放子集
          for(var i in this.listAll) {//获得点击行的子集
            if(this.listAll[i].parentId === row.deptId) {
              addArr.push(this.listAll[i]);
            }
          }
          for(var i in this.listAll) { //获得子集的子集
              for(var j in addArr) {
                if(this.listAll[i].parentId === addArr[j].deptId) {
                  addArr.push(this.listAll[i]);
                }
              }
          }

          var delArr = [];//放删除的数组
          for(var i in this.list) {//虽然有这么多子集，但是不一定真的在list中全部显示，找出在list中已经显示的子集
              for(var j in addArr) {
                  if(this.list[i].deptId === addArr[j].deptId) {
                      delArr.push(addArr[j]);
                  }
              }
          }
          var del; //子集应该删除在list中的位置
          for(var j in this.list) {
            if(this.list[j].deptId ===row.deptId) {
              del = Number(j) + 1;
            }
          }

          //正式删除
          for(var k in delArr) {
            this.list.splice(del,1);
            //把状态改成false
            for(var i in this.list) {
              if(this.list[i].deptId === row.deptId) {
                this.list[i].status = true;
              }
            }
          }
        }
      },
      searchRows() {
        if(this.searchList.deptName=== '') {
          this.fetchData()
        }else {
          Dept.getDepartmentList(this.searchList).then(data => {
            this.list = data;
          })
        }
      },
      emptyInputs() {
        this.searchList = {};
        this.fetchData()
      },
      createRow() {
        this.create_visible = true;
        this.form_create = {};
        this.getDeptList();
      },
      submitCreateForm() {
        var keys = this.$refs.tree.getCheckedKeys().splice(-1,1);
        this.form_create.parentId = keys.join(',');  //只能选择一个部门，所以以最后一个勾选的为准

        //console.log('this.form_create',this.form_create);
        Dept.createMenu(this.form_create).then(data => {
          this.create_visible = false;
          this.fetchData();
        })
      },
      editRow() {
          console.log('打开编辑框,',this.editDept);
        this.getDeptList();
        if(this.$refs.tree) { //只有第二次打开dialog才会加载好树形结构
          this.$refs.tree.setCheckedNodes([]);//清空已选的
          this.editDept = []; //清空展开项
          console.log('如果有树结构的话',this.editDept);
          console.log('如果有树结构的话',this.editDept);
        }
        if(this.multipleSelection.length === 0) {
          alert('请先勾选行');
        }else if(this.multipleSelection.length >= 2) {
          alert('每次最多勾选一行');
        }else if(this.multipleSelection.length === 1){
          Dept.detailRow({deptId:this.multipleSelection[0].deptId}).then(data => {
            this.edit_visible = true;
            //不能获取所有数据，否则报错
            this.form_edit.deptName = data.msg.deptName;
            this.form_edit.oldDeptName = data.msg.deptName;
            this.form_edit.deptId = data.msg.deptId;
            this.form_edit.parentId = data.msg.parentId;
            //只有第二次打开dialog才会加载好树形结构
            if( this.$refs.tree) {//第二次打开时 勾选
              this.$refs.tree.setCheckedKeys([data.msg.parentId]);
              this.editDept.push(data.msg.parentId); //第二次打开之后 的展开项
            }else {
              this.editDept.push(data.msg.parentId); //第一次打开时，勾选
            }

          })

        }

      },
      submitEditForm() {
        var keys = this.$refs.tree.getCheckedKeys().splice(-1,1);
        this.form_edit.parentId = keys.join(',');  //只能选择一个部门，所以以最后一个勾选的为准
        console.log('this.form_edit',this.form_edit);
        Dept.updateMenu(this.form_edit).then(data => {
          this.edit_visible = false;
          this.fetchData();
        })
      },
      detailRow(row) {},
      deleteRow() {
        if(this.multipleSelection.length === 0) {
          alert('请先勾选行');
        }else if(this.multipleSelection.length >= 2) {
          alert('每次最多勾选一行');
        }else if(this.multipleSelection.length === 1){
          this.$confirm('是否删除该条数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            Dept.delRow({ids:this.multipleSelection[0].deptId}).then(data => {
              this.fetchData(this.currentPage);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            })

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      getDeptList() {
        this.treeDeptData = [];  //先清空数据
        function getTree(data,parentData) {
          var childrenArr = [] //所有非一级父元素的集合
          for(var i=0;i<data.length;i++) {
            var obj = {};
            var objChildrens = {};
            if(data[i].parentId === 0) { //parentId是0,说明是父元素，它的里面可能会有子集
              obj.label=data[i].deptName;
              obj.deptId=data[i].deptId;
              obj.parentId=data[i].parentId;
              obj.children = [];
              parentData.push(obj);
            }else { //找到所有的子集 装在childrenArr
              objChildrens.label=data[i].deptName;
              objChildrens.deptId=data[i].deptId;
              objChildrens.parentId=data[i].parentId;
              objChildrens.children = [];
              childrenArr.push(objChildrens);
            }
          }
          //二级菜单装入一级菜单
          var lever2Arr = [];
          for(var i in parentData) {
            for(var j in childrenArr) {
              if(parentData[i].deptId === childrenArr[j].parentId) {
                parentData[i].children.push(childrenArr[j]);
                lever2Arr.push(childrenArr[j])
              }
            }
          }
          getTreeChildren(parentData,childrenArr,lever2Arr);
        }
        function getTreeChildren(parentData,childrenArr,lever2Arr) {
          //找到三级菜单
          var lever3Arr = [];
          for(var i in childrenArr) {
            for(var j in lever2Arr) {
              if(lever2Arr[j].deptId === childrenArr[i].parentId) {
                lever3Arr.push(childrenArr[i])
              }
            }
          }
          //三级放入
          for(var i in lever3Arr) {
            for(var j in parentData) {
              for(var k in parentData[j].children) {
                if(parentData[j].children[k].deptId === lever3Arr[i].parentId) {
                  parentData[j].children[k].children.push(lever3Arr[i]);
                  getTreeChildren(parentData[j].children,childrenArr,lever3Arr);
                }
              }
            }
          }

        }


        Dept.getDepartmentList().then(data => {
          //console.log('获得的tree数据',data);
          getTree(data,this.treeDeptData);
          console.log('整理后的tree数据',this.treeDeptData);
        })
      },

      handleClick(data,checked, node) {
        this.i_tree++;
        if(this.i_tree%2==0){
          if(checked){
            this.$refs.tree.setCheckedNodes([]);
            this.$refs.tree.setCheckedNodes([data]);
            //交叉点击节点
          }else{
            this.$refs.tree.setCheckedNodes([]);
            //点击已经选中的节点，置空
          }
        }
      },
      changePage(p) {
        this.fetchData(p)
      },
    },
    computed: {
      tableHeight() {
        const filterHeight = 28
        var tableHeight = this.getTableHeight(filterHeight)
        return tableHeight;
      }
    }
  }
</script>
